package com.photoeditor.demo.ui.adapter.home;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.res.Resources;
import android.support.constraint.ConstraintLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.common.base.utils.DeviceUtils;
import com.common.base.utils.thread.ThreadPool;
import com.photoeditor.R;
import com.photoeditor.demo.imageloader.ImageLoader;
import com.photoeditor.demo.model.bean.IItemBean;
import com.photoeditor.demo.model.bean.TitleBean;
import com.photoeditor.demo.model.store.download.DownloadUtils;
import com.photoeditor.demo.model.store.download.IDownloadListener;
import com.photoeditor.demo.model.store.module.BaseOnlineManager;
import com.photoeditor.demo.model.store.module.StoreOnlineBean;
import com.photoeditor.demo.model.store.module.StoreOnlineManager;
import com.photoeditor.demo.model.subscribe.manager.AppVipManager;
import com.photoeditor.demo.ui.activity.GalleryActivity;
import com.photoeditor.demo.ui.activity.effect.FilterDetailActivity;
import com.photoeditor.demo.ui.activity.effect.StickerDetailActivity;
import com.photoeditor.demo.ui.fragement.ItemClickSupport;
import com.photoeditor.demo.ui.widget.DownloadApplyButton;
import com.photoeditor.demo.util.FontUtil;
import com.photoeditor.demo.util.PluginVersionUtil;
import com.photoeditor.demo.util.ToastUtil;

import java.lang.ref.WeakReference;
import java.util.ArrayList;

import static com.photoeditor.demo.model.bean.IItemBean.TYPE_AD;
import static com.photoeditor.demo.util.store.StoreConstant.store.storeEntrance.ENTRANCE_HOMEPAGE;

public class HomeAdapter extends BaseMultiItemQuickAdapter<MultiItemEntity, BaseViewHolder> {

    public static final int TYPE_TITLE = 100;
    public static final int TYPE_BASE_ITEM = 102;

    private Activity mContext;
    private boolean mIsVip;
    public static boolean isShowVipView=false;

    private ItemClickSupport mItemClickSupport;
    private int itemCount = 0;

    private View.OnClickListener mOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mItemClickSupport != null) {
                mItemClickSupport.onItemClick(v);
            }
        }
    };

    public void setItemClickSupport(ItemClickSupport support) {
        mItemClickSupport = support;
    }

    public HomeAdapter(Activity context) {
        super(new ArrayList<MultiItemEntity>());
        mContext = context;
        mIsVip = AppVipManager.isVip();
        addItemType(TYPE_TITLE, R.layout.item_title);
        addItemType(TYPE_BASE_ITEM, R.layout.item_base);
        addItemType(TYPE_AD, R.layout.item_entrance_ad);
    }

    @Override
    protected void convert(BaseViewHolder helper, MultiItemEntity item) {
        int type = item.getItemType();
        switch (type) {
            case TYPE_TITLE:
                TextView textView = helper.getView(R.id.tv_title);
                textView.setText(((TitleBean) item).getTitle());
                FontUtil.setAvenirFontHeavy(textView);
                itemCount++;
                break;
//            case TYPE_AD:
//                EntranceAdView entranceAdView = (EntranceAdView) helper.itemView;
//                entranceAdView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
//                int margin = DeviceUtils.dip2px(4);
//                entranceAdView.setMargin(margin, margin, 0, 0, 0);
//                AdItemBean bean = (AdItemBean) item;
//                if (!bean.hasAd()) {
//                    ((ViewGroup) entranceAdView).removeAllViews();
//                    return;
//                }
//
//                bean.setNeedLimitAdHeight(true);
//                bean.setMaxCoverHeight(DeviceUtils.dip2px(220));
//                ((EntranceAdView) entranceAdView).setData(bean);
//                break;
            case TYPE_BASE_ITEM:
                itemCount++;
                if (itemCount == 2){
                    setComingSoonItem(helper, item);
                    break;
                }else if (itemCount == getItemCount()){
                    itemCount = 0;
                }

                final StoreOnlineBean storeOnlineBean = (StoreOnlineBean) item;
                boolean isInstalled = StoreOnlineManager.isInstalledByPkgName(storeOnlineBean.getPkgName());
                ImageView logo = helper.getView(R.id.img_logo);
                TextView name = helper.getView(R.id.tv_name);
                final DownloadApplyButton downloadApplyButton = helper.getView(R.id.download_apply_btn);
                LinearLayout dwnloadButtonLayout = helper.getView(R.id.lly_download);
                String nameStr = storeOnlineBean.getName().replaceAll("[A-Z]", " $0");//正则替换注意“ $0”前面有个空格
                name.setText(nameStr);
                int storeBeanType = 0;
                if (storeOnlineBean.getDownUrl().contains("sticker")) {
                    storeBeanType = IItemBean.TYPE_STICKER;
                    ImageLoader.loadImage(storeOnlineBean.getBanner(), logo);
                } else if (storeOnlineBean.getDownUrl().contains("filter")) {
                    storeBeanType = IItemBean.TYPE_FILTER;
                    ImageLoader.loadImage(storeOnlineBean.getIcon(), logo);
                }
                final int finalStoreBeanType = storeBeanType;
                if (!mIsVip && storeOnlineBean.isBuy()) {
                    helper.getView(R.id.img_vip).setVisibility(View.VISIBLE);
                } else {
                    helper.getView(R.id.img_vip).setVisibility(View.INVISIBLE);
                }
                FontUtil.setCustomFontMedium(name);
                Object tag = downloadApplyButton.getTag();
                if (tag instanceof DownloadListener) {
                    DownloadUtils.getInstance().removeListener((IDownloadListener) tag);
                }
                downloadApplyButton.setStatus(isInstalled);
                if (isInstalled) {
                    //已安装，直接应用
                    dwnloadButtonLayout.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            applyItem(finalStoreBeanType, storeOnlineBean);
                        }
                    });
                } else {
                    //未安装，开始下载
                    dwnloadButtonLayout.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (!StoreOnlineManager.isInstalledByPkgName(storeOnlineBean.getPkgName())) {
                                if (!downloadApplyButton.isDownloading()) {
                                    downloadResource(storeOnlineBean, downloadApplyButton, finalStoreBeanType);
                                }
                            } else {
                                //已安装，直接应用
                                applyItem(finalStoreBeanType, storeOnlineBean);
                            }
                        }
                    });
                }
                helper.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (finalStoreBeanType == IItemBean.TYPE_STICKER) {
                            if(helper.getView(R.id.img_vip).getVisibility()==View.VISIBLE){
                                isShowVipView=true;
                            }else{
                                isShowVipView=false;
                            }
                            StickerDetailActivity.startActivity(mContext, storeOnlineBean, ENTRANCE_HOMEPAGE);
                        } else if (finalStoreBeanType == IItemBean.TYPE_FILTER) {
                            if(helper.getView(R.id.img_vip).getVisibility()==View.VISIBLE){
                                isShowVipView=true;
                            }else{
                                isShowVipView=false;
                            }
                            FilterDetailActivity.startActivity(mContext, storeOnlineBean, FilterDetailActivity.ENTRANCE_STORE,
                                    ENTRANCE_HOMEPAGE);
                        }
                    }
                });

                IDownloadListener iDownloadListener = createNewListener(storeOnlineBean, downloadApplyButton);
                downloadApplyButton.setTag(iDownloadListener);
                DownloadUtils.getInstance().addListener(iDownloadListener);
                break;
            default:
                break;
        }
    }

    //设置第一个缩略图为预告图
    private void setComingSoonItem(BaseViewHolder helper, MultiItemEntity item) {
        String path = ContentResolver.SCHEME_ANDROID_RESOURCE + "://"
                + mContext.getResources().getResourcePackageName(R.drawable.ic_coming_soon) + "/"
                + mContext.getResources().getResourceTypeName(R.drawable.ic_coming_soon) + "/"
                + mContext.getResources().getResourceEntryName(R.drawable.ic_coming_soon);//得到资源文件中图片的path
        ImageView logo = helper.getView(R.id.img_logo);
        ImageLoader.loadImage(path, logo);

        TextView name = helper.getView(R.id.tv_name);
        ConstraintLayout.LayoutParams layoutParams = (ConstraintLayout.LayoutParams) name.getLayoutParams();
        layoutParams.topMargin = DeviceUtils.dip2px(35);
        name.setLayoutParams(layoutParams);
        name.setText("Animal Face");
        helper.getView(R.id.lly_download).setVisibility(View.GONE);

        helper.itemView.setClickable(false);
    }

    public static boolean isIsShowVipView(){
        return isShowVipView;
    }

    private void applyItem(int finalStoreBeanType, StoreOnlineBean storeOnlineBean) {
        if (finalStoreBeanType == IItemBean.TYPE_STICKER) {
            if (PluginVersionUtil.verifyPluginVersion(mContext, BaseOnlineManager.STORE_FUNC_TYPE_STICKER, storeOnlineBean.getVersioncode())) {
                GalleryActivity.startGallerySelectImageToAddSticker(mContext, storeOnlineBean.getPkgName(), "");
            }
        } else if (finalStoreBeanType == IItemBean.TYPE_FILTER) {
            if (PluginVersionUtil.verifyPluginVersion(mContext, BaseOnlineManager.STORE_FUNC_TYPE_FILTER, storeOnlineBean.getVersioncode())) {
                GalleryActivity.startGallerySelectImageToApplyFilter(mContext, storeOnlineBean.getPkgName(), "");
            }
        }
    }

    @Override
    public long getItemId(int position) {
        long id;

        id = mData.get(position).getItemType();

        return id;
    }

    private void downloadResource(final StoreOnlineBean storeOnlineBean, DownloadApplyButton downloadApplyButton, int beanType) {
        int type = 0;
        if (beanType == IItemBean.TYPE_STICKER) {
            type = BaseOnlineManager.STORE_FUNC_TYPE_STICKER;
        } else if (beanType == IItemBean.TYPE_FILTER) {
            type = BaseOnlineManager.STORE_FUNC_TYPE_FILTER;
        }
        DownloadUtils.getInstance().startDownload(storeOnlineBean, type);
    }

    private IDownloadListener createNewListener(StoreOnlineBean bean, DownloadApplyButton downloadApplyButton) {
        return new DownloadListener(bean.getPkgName(), downloadApplyButton);
    }

    private static class DownloadListener implements IDownloadListener {

        private String mDownloadId;
        private WeakReference<DownloadApplyButton> mRef;

        public DownloadListener(String downloadId, DownloadApplyButton view) {
            mDownloadId = downloadId;
            mRef = new WeakReference<>(view);
        }

        @Override
        public String getDownloadId() {
            return mDownloadId;
        }

        @Override
        public void onProgressUpdate(final String downloadId, final int progress) {
            if (!TextUtils.isEmpty(downloadId) && mDownloadId.equals(downloadId)) {
                ThreadPool.runUITask(new Runnable() {
                    @Override
                    public void run() {
                        if (mRef.get() != null) {
                            mRef.get().setProgress(progress);
                        }
                    }
                });
            }
        }

        @Override
        public void onFailed(final String downloadId) {
            if (!TextUtils.isEmpty(downloadId) && mDownloadId.equals(downloadId)) {
                ToastUtil.showToast(R.string.filter_download_failed);
                ThreadPool.runUITask(new Runnable() {
                    @Override
                    public void run() {
                        if (mRef.get() != null) {
                            mRef.get().setDownloadFailedStatus();
                        }
                    }
                });
            }
        }

        @Override
        public String getFullActivityName() {
            return "";
        }
    }

    public void setVip(boolean vip) {
        mIsVip = vip;
    }

}
